import {Login} from '@/api/login'

import {setToken,setUserName,getUserName} from '@/utils/app'



const state = {
    isCollapse: JSON.parse(sessionStorage.getItem('isCollapse')) || false,
    token:'',
    username: getUserName() || ''
    
}
const getters = {
    isCollapse: state => state.isCollapse
}

//mutations 执行同步操作，没有回调
const mutations = {
    SET_COLLSPSE(state) {
        state.isCollapse = !state.isCollapse;
        sessionStorage.setItem('isCollapse', JSON.stringify(state.isCollapse));
    },

    SET_TOKEN(state,value){
        state.token = value;
    },

    SET_USERNAME(state,value){
        state.username = value;
    }
}

//可以有回调处理
const actions = {
    login({commit},params){
        return new Promise((resolve,reject) => {
            Login(params).then(response=>{
                let data = response.data.data;
                console.info('login success');
                console.info(data);
                commit('SET_TOKEN',data.token);
                commit('SET_USERNAME',data.username)

                setToken(data.token)
                setUserName(data.username);

                resolve(response)
            }).catch(error=>{
                reject(error)
            })
        })
    }

}

export default {
    namespaced:true,
    state, 
    getters, 
    mutations, 
    actions
}